import java.io.*;
import java.util.*;

public class WordSort 
{
	public static void main(String[] args) throws IOException
	{
		if ( args.length < 2 ) {
			System.out.println("Usage: WordSort inputfile outputfile");
			return;
		}
		String inputfile = args[0];
		String outputfile = args[1];

		/* Create the word map. Each key is a word and each value is an
		Integer that represents the number of times the word occurs
		in the input file.
		*/
		Map<String,Integer> map = new TreeMap<String,Integer>();

		Scanner scanner = new Scanner( new File(inputfile) );
		while ( scanner.hasNext() ) {
			String word = scanner.next();
			Integer count = map.get( word );
			count = ( count == null ? 1 : count +1 );
			map.put( word, count );
		}
		scanner.close();

		// Get the map's keys
		List<String> keys = new ArrayList<String>( map.keySet() );
		Collections.sort( keys );
		List<Integer> values= new ArrayList<Integer>(map.values());
		// create comparator for reverse order
		Comparator<Integer> cmp = Collections.reverseOrder();
		// sort the list
		Collections.sort(values, cmp);

		// Write the results to the output file
		PrintWriter out = new PrintWriter( new FileWriter(outputfile) );
		for ( String key : keys )
			out.println( key + " : " + map.get(key) );

		out.println("===============================================");
		out.println("The top 3 most occuring items are: ");
		Map<Integer, String> map2 = new TreeMap<Integer, String>();
		for ( String key : keys ) {
			Integer cnt = map.get(key);
			if(cnt == values.get(0))
				map2.put( 1, key );
			if(cnt == values.get(1))
				map2.put( 2, key );
			if(cnt == values.get(2))
				map2.put( 3, key );
		}
		out.println( map2.get(1) + " : " + map.get(map2.get(1)) );
		out.println( map2.get(2) + " : " + map.get(map2.get(2)) );
		out.println( map2.get(3) + " : " + map.get(map2.get(3)) );
		out.close();
	}
}
